package com.molichuxing.gateway.utils;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.gateway.bff.user.entity.response.UserVo;
import com.molichuxing.gateway.utils.contants.RequestAttrConst;

/**
 * request获取参数工具类
 * 
 * @author zoumingyu
 * @date 2019年9月9日
 *
 */
public class RequestAttrUtil {

	/**
	 * 获取当前用户信息
	 *
	 * @return
	 */
	public static UserVo getCurrentUser() {
		Object obj = getAttributeValue(RequestAttrConst.USER_KEY);
		UserVo userVo = obj == null ? null : JSONObject.parseObject(JSON.toJSONString(obj), UserVo.class);
		if(null == userVo) {
			throw new BizException(ResponseCodeEnum.LOGIN_ERROR.getCode(),ResponseCodeEnum.LOGIN_ERROR.getMessage());
		}
		return userVo;
	}

	/**
	 * 获取当前用户关id
	 *
	 * @return
	 */
	public static Integer getCurrentUserId() {
		UserVo userVo = getCurrentUser();
		if(null == userVo) {
			throw new BizException(ResponseCodeEnum.LOGIN_ERROR.getCode(),ResponseCodeEnum.LOGIN_ERROR.getMessage());
		}
		return userVo.getUserId();
	}

	private static Object getAttributeValue(String name) {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
				.currentRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();

		return request.getAttribute(name);
	}
}
